<template>
  <div class="marketStrategy-container" style="padding: 10px 20px;">
    <!--搜索框-->
    <div class="market-top">
      <div class="market-top-search">
        <div class="flex gap-4 mb-4">
          <el-input
              v-model="input2"
              style="width: 240px"
              placeholder="请输入需要搜索的内容..."
              :prefix-icon="Search"
          />
          <el-button style="margin-left: 5px;">搜索</el-button>
        </div>
      </div>
      <!--右侧按钮-->
      <div class="market-top-btn">
        <el-button type="primary" @click="dialogFormVisible1 = true">添加营销策略</el-button>
      </div>
    </div>
    <!--添加营销策略弹出框-->
    <el-dialog v-model="dialogFormVisible1" title="新增营销策略" width="800" draggable overflow align-center>
      <div class="input-group">
        <el-form ref="formRef" :model="addFormData" label-width="auto" class="demo-ruleForm" status-icon
                 :rules="rules">
          <el-form-item label="营销策略名称" prop="marketPloyName" style="width:400px;" label-position="left">
            <el-input v-model="addFormData.marketPloyName" autocomplete="off" />
          </el-form-item>
          <el-form-item required style="display:flex;flex-direction:row;"   label="公司名称:" prop="companyName" label-position="left">
            <el-select style="width:95%" filterable v-model="addFormData.companyIdTwo" placeholder="请选择公司" @change="handle">
              <el-option v-for="option in options" :key="option.customerCompanyId"
                         :label="option.customerCompanyName" :value="option.customerCompanyId">
              </el-option>
            </el-select>
            <el-icon style="width:30px;height:31px;border:1px solid #dcdfe6;border-radius: 5px;"><CirclePlus /></el-icon>
          </el-form-item>
          <el-form-item required label="能源类型:" label-position="left">
            <el-radio-group v-model="addFormData.energyType">
              <el-radio label="11">CNG</el-radio>
              <el-radio label="12">LNG</el-radio>
              <el-radio label="21">H2</el-radio>
              <el-radio label="31">92</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item required label="开始时间" prop="timePlanStart" label-position="left">
                <div class="block">
                  <el-date-picker
                      v-model="addFormData.timePlanStart"
                      type="datetime"
                      placeholder="计划开始时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      date-format="MMM DD, YYYY"
                      time-format="HH:mm"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item required label="结束时间" prop="timePlanEnd" label-position="left">
                <div class="block">
                  <el-date-picker
                      v-model="addFormData.timePlanEnd"
                      type="datetime"
                      placeholder="计划结束时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      date-format="MMM DD, YYYY"
                      time-format="HH:mm"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item required label="优惠类型" prop="discountType" style="width:400px;" label-position="left">
                <el-radio-group v-model="addFormData.discountType">
                  <el-radio  value="3">加注满减金额</el-radio>
                  <el-radio  value="4">加注满送金额</el-radio>
                  <el-radio  value="5">加注满减比例</el-radio>
                  <el-radio  value="6">加注满送比例</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-for="(item, index) in addFormData.ladderThreshold" :key="index">
            <el-form-item required label="阶梯优惠" :prop="'ladderThreshold.' + index + '.startAmount'" style="width:100%;" label-position="left">
              <el-row>
                <!-- 开始金额 -->
                <el-col :span="6">
                  <el-input v-model="item.startAmount" autocomplete="off" placeholder="开始金额" autosize></el-input>
                </el-col>
                <!-- 中间的波浪号 -->
                <el-col :span="1" style="text-align: center; line-height: 36px;">
                  <label>~</label>
                </el-col>
                <!-- 结束金额/比例 -->
                <el-col :span="6">
                  <el-input v-model="item.endAmountOrRate" autocomplete="off" placeholder="结束金额" autosize></el-input>
                </el-col>
                <!-- 描述（金额/比例） -->
                <el-col :span="6" style="margin-left: 10px;"> <!-- 添加一些间距 -->
                  <el-input v-model="item.description" autocomplete="off" placeholder="金额/比例" autosize></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="resetForm(addFormData)" size="large"
                   style="width:100px;text-decoration-style: wavy;">重置</el-button>
        <el-button type="primary" @click="submitForm(addFormData)" size="large" style="width:100px">提交</el-button>
      </template>
    </el-dialog>
    <!--编辑营销策略弹出框 -->
    <el-dialog v-model="dialogUpdateVisible" title="编辑营销策略" width="800" draggable overflow align-center>
      <div class="input-group">
        <el-form ref="formRef" :model="updateFormData" label-width="auto" class="demo-ruleForm" status-icon
                 :rules="rules">
          <el-form-item label="营销策略名称" prop="marketPloyName" style="width:400px;" label-position="left">
            <el-input v-model="updateFormData.marketPloyName" autocomplete="off" />
          </el-form-item>
          <el-form-item required style="display:flex;flex-direction:row;"   label="公司名称:" prop="companyIdTwo" label-position="left">
            <el-select style="width:95%" filterable v-model="updateFormData.companyIdTwo" placeholder="请选择公司" @change="handle">
              <el-option v-for="option in options" :key="option.customerCompanyId"
                         :label="option.customerCompanyName" :value="option.customerCompanyId">
              </el-option>
            </el-select>
            <el-icon style="width:30px;height:31px;border:1px solid #dcdfe6;border-radius: 5px;"><CirclePlus /></el-icon>
          </el-form-item>
          <el-form-item required label="能源类型:" label-position="left">
            <el-radio-group v-model="updateFormData.energyType">
              <el-radio label="11">CNG</el-radio>
              <el-radio label="12">LNG</el-radio>
              <el-radio label="21">H2</el-radio>
              <el-radio label="31">92</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item required label="开始时间" prop="timePlanStart" label-position="left">
                <div class="block">
                  <el-date-picker
                      v-model="updateFormData.timePlanStart"
                      type="datetime"
                      placeholder="计划开始时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      date-format="MMM DD, YYYY"
                      time-format="HH:mm"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item required label="结束时间" prop="timePlanEnd" label-position="left">
                <div class="block">
                  <el-date-picker
                      v-model="updateFormData.timePlanEnd"
                      type="datetime"
                      placeholder="计划结束时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      date-format="MMM DD, YYYY"
                      time-format="HH:mm"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item required label="优惠类型" prop="discountType" style="width:400px;" label-position="left">
                <el-radio-group v-model="updateFormData.discountType">
                  <el-radio  value="3">加注满减金额</el-radio>
                  <el-radio  value="4">加注满送金额</el-radio>
                  <el-radio  value="5">加注满减比例</el-radio>
                  <el-radio  value="6">加注满送比例</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-for="(item, index) in updateFormData.ladderThreshold" :key="index">
            <el-form-item required label="阶梯优惠" :prop="'ladderThreshold.' + index + '.startAmount'" style="width:100%;" label-position="left">
              <el-row>
                <!-- 开始金额 -->
                <el-col :span="6">
                  <el-input v-model="item.startAmount" autocomplete="off" placeholder="开始金额" autosize></el-input>
                </el-col>

                <!-- 中间的波浪号 -->
                <el-col :span="1" style="text-align: center; line-height: 36px;">
                  <label>~</label>
                </el-col>

                <!-- 结束金额/比例 -->
                <el-col :span="6">
                  <el-input v-model="item.endAmountOrRate" autocomplete="off" placeholder="结束金额" autosize></el-input>
                </el-col>

                <!-- 描述（金额/比例） -->
                <el-col :span="6" style="margin-left: 10px;"> <!-- 添加一些间距 -->
                  <el-input v-model="item.description" autocomplete="off" placeholder="金额/比例" autosize></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="resetForm(formRef)" size="large" style="width:100px;text-decoration-style: wavy;">重置</el-button>
        <el-button type="primary" @click="updataForm(formRef)" size="large" style="width:100px">提交</el-button>
      </template>
    </el-dialog>
    <!--表格部分-->
    <div class="market-table">
      <!--如果请求请求表格里还没有数据，显示加载-->
      <el-table :data="tableData"  border style="width: 100%;margin-top: 20px;">
        <el-table-column show-overflow-tooltip  v-for="column in allColumns" :key="column.prop" :prop="column.prop" :label="column.label" align="center">
        </el-table-column>
        <el-table-column label="优惠阶梯" align="center">
<!--          <template #default="scope">-->
<!--            <div v-for="(ladder, index) in scope.row.parsedLadders" :key="index">-->
<!--            </div>-->
<!--          </template>-->
          <el-table-column prop="startAmount" label="起始金额" width="120" align="center" />
          <el-table-column prop="endAmount" label="结束金额" width="120" align="center" />
          <el-table-column prop="giftAmount" label="赠送金额/比例" width="120" align="center" />
        </el-table-column>
        <!--操作-->
        <el-table-column fixed="right" width="150" label="操作" align="center">
          <template #default="scope">
            <el-row>
              <el-col :span="12">
                <el-button color="#409eff" :dark="isDark" @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
<!--                <span class="table-btn" @click="handleEdit(scope.$index, scope.row)">编辑</span>-->
              </el-col>
              <!-- 删除提示框 -->
              <el-popconfirm
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="Are you sure to delete this?"
                  @confirm="handleDelete(scope.$index, scope.row)"
                  @cancel="cancelEvent"
              >
                <template #reference>
                  <el-col :span="12">
<!--                    <span  class="table-btn">删除</span>-->
                    <el-button color="#409eff" :dark="isDark" plain >删除</el-button>
                  </el-col>
                </template>
              </el-popconfirm>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="market-bottom">
      <!--分页器-->
      <el-pagination class="page" background layout="total,sizes,prev, pager, next,jumper" size="small" :total="pageData.total"
                     :page-sizes="[20, 30 , 100 ,200]" v-model:current-page="pageData.currentPage" v-model:page-size="pageData.pageSize"
                     @change="handleChange" />
    </div>
  </div>
</template>
<script setup>
import { ref,onMounted,reactive } from 'vue'
import {Calendar, CirclePlus, Search} from '@element-plus/icons-vue'
import {getMarketPloyInfo, postAddMarketPloyInfo, postDeleteMarketPloyInfo} from '@/api/marketStrategy.js'
import {getCustomerList} from '@/api/customer.js'
import {ElFormItem, ElInput} from "element-plus";
const input2 = ref('')
const tableForm = ref({
  value:[] //初始化为空数组
})
const tableData = ref([])

let options = ref([])
// 控制表格显示列
const allColumns = [
  // {prop:"marketPloyId" , label :"营销策略ID" },
  // {prop:"companyIdTwo" , label :"关联-公司ID" },
  {prop :"companyName" , label :"公司名称" },
  {prop :"marketPloyName" , label :"营销策略名称" },
  {prop :"energyType" , label :"能源类型" },
  {prop :"marketPloyState" , label :"营销策略申请状态" },
  {prop :"marketPloyStateEnable" , label :"营销策略启用状态" },
  {prop :"timePlanStart" , label :"计划开始时间" },
  {prop :"timePlanEnd" , label :"计划结束时间" },
  {prop :"discountType" , label :"优惠类型" },
  // {prop :"startAmount" , label :"起始金额" }, // 新增列
  // {prop :"endAmount" , label :"结束金额" },   // 新增列
  // {prop :"giftAmount" , label :"赠送金额" },
  // {prop :"ladderThreshold" , label :"加注优惠单价" },
  // { prop: 'formattedLadderThreshold', label: '阶梯阈值' },
  {prop :"applyBy" , label :"申请人" },
  {prop :"timeApply" , label :"申请时间" },
  {prop :"verifyBy" , label :"审核人" },
  {prop :"timeVerify" , label :"审核时间" },
]

// 添加营销策略
const addFormData = reactive({
  marketPloyId:'',//营销策略ID
  companyIdTwo:'',//关联-公司ID
  marketPloyName: '',
  energyType: '12',
  marketPloyState: '',//营销策略申请状态(Ex:0.申请中|1.撤销|2.删除|3.同意(审核通过)|4.拒绝(审核未通过)
  marketPloyStateEnable: '',//营销策略启用状态(Ex:0.未启用|1.已启用.已生效|2.已启用.待生效|3.失效)
  timePlanStart: '',//计划开始时间;Ex:YYYY-MM-DD HH:MM:SS
  timePlanEnd: '',
  discountType: '',
  // ladderThreshold: '',
  // 初始化阶梯优惠数据
  ladderThreshold: [
    { description:"",startAmount: '', endAmountOrRate: '', },
    { description:"",startAmount: '', endAmountOrRate: '', },
    { description:"",startAmount: '', endAmountOrRate: '', }
  ],
  applyBy: '',
  timeApply: '',
  verifyBy: '',
  timeVerify: '',
})
// 编辑营销策略
const formRef = ref(null);
const updateFormData = reactive({
  marketPloyId:'',//营销策略ID
  companyIdTwo:'',//关联-公司ID
  marketPloyName: '',
  energyType: '12',
  marketPloyState: '',//营销策略申请状态(Ex:0.申请中|1.撤销|2.删除|3.同意(审核通过)|4.拒绝(审核未通过)
  marketPloyStateEnable: '',//营销策略启用状态(Ex:0.未启用|1.已启用.已生效|2.已启用.待生效|3.失效)
  timePlanStart: '',//计划开始时间;Ex:YYYY-MM-DD HH:MM:SS
  timePlanEnd: '',
  discountType: '',
  // ladderThreshold: '',
  ladderThreshold: [],  // 初始化阶梯优惠数据
  applyBy: '',
  timeApply: '',
  verifyBy: '',
  timeVerify: '',
})
// 控制新增弹出框
const dialogFormVisible1 = ref(false)
// 控制打开编辑弹窗
const dialogUpdateVisible = ref(false)
//定义验证规则
const rules = {
  marketPloyName: [
    { required: true, message: '请输入营销策略名称', trigger: 'blur' },
  ]
}
// 分页器数据
const pageData = reactive({
  total: 0, //默认
  pageSize: 30,
  currentPage: 1
})
const transformArray = (arr) => {
  arr.forEach(obj => {
    // 处理营销策略申请状态
    if (obj.marketPloyState === 0) obj.marketPloyState = "申请中";
    else if (obj.marketPloyState === 1) obj.marketPloyState = "撤销";
    else if (obj.marketPloyState === 2) obj.marketPloyState = "删除";
    else if (obj.marketPloyState === 3) obj.marketPloyState = "同意(审核通过)";
    else if (obj.marketPloyState === 4) obj.marketPloyState = "拒绝(审核未通过)";

    // 处理营销策略启用状态
    if (obj.marketPloyStateEnable === 0) obj.marketPloyStateEnable = "未启用";
    else if (obj.marketPloyStateEnable === 1) obj.marketPloyStateEnable = "已启用.已生效";
    else if (obj.marketPloyStateEnable === 2) obj.marketPloyStateEnable = "已启用.待生效";
    else if (obj.marketPloyStateEnable === 3) obj.marketPloyStateEnable = "失效";

    // 处理优惠类型
    if (obj.discountType === 2) obj.discountType = "优惠单价";
    else if (obj.discountType === 3) obj.discountType = "加注满减金额";
    else if (obj.discountType === 8) obj.discountType = "固定金额满送";
    else if (obj.discountType === 9) obj.discountType = "固定折扣满送";
    else if (obj.discountType === 10) obj.discountType = "阶梯优惠满送";
    else if (obj.discountType === 11) obj.discountType = "固定金额满减";

    // 处理能源类型
    if (obj.energyType === 11) obj.energyType = "CNG";
    else if (obj.energyType === 12) obj.energyType = "LNG";
    else if (obj.energyType === 21) obj.energyType = "H2";
    else if (obj.energyType === 31) obj.energyType = "0#";
    else if (obj.energyType === 32) obj.energyType = "92#";
    else if (obj.energyType === 33) obj.energyType = "95#";
    else if (obj.energyType === 34) obj.energyType = "98#";

    // 解析并格式化 ladderThreshold
    // 解析并格式化 ladderThreshold 并添加回原对象
    if (obj.ladderThreshold) {
      const ladderThreshold = JSON.parse(obj.ladderThreshold);
      obj.parsedLadders = [];

      for (const [giftAmount, range] of Object.entries(ladderThreshold)) {
        const startAmount = parseFloat(range[0]);
        const endAmount = parseFloat(range[range.length - 1]);
        obj.parsedLadders.push({
          giftAmount: parseFloat(giftAmount),
          startAmount,
          endAmount
        });
      }
    }
  });
  return arr;
};
// 编辑按钮
const handleEdit = (index,row) =>{
  //打开修改弹窗
  dialogUpdateVisible.value = true;
  // 将当前行的数据复制到 updateFormData
  updateFormData.marketPloyId = row.marketPloyId;
  updateFormData.companyIdTwo = row.companyIdTwo;
  updateFormData.marketPloyName = row.marketPloyName;
  updateFormData.energyType = row.energyType;
  updateFormData.marketPloyState = row.marketPloyState;
  updateFormData.marketPloyStateEnable = row.marketPloyStateEnable;
  updateFormData.timePlanStart = row.timePlanStart;
  updateFormData.timePlanEnd = row.timePlanEnd;
  updateFormData.discountType = row.discountType;
  updateFormData.ladderThreshold = row.ladderThreshold ? JSON.parse(row.ladderThreshold) : [];
  updateFormData.applyBy = row.applyBy;
  updateFormData.timeApply = row.timeApply;
  updateFormData.verifyBy = row.verifyBy;
  updateFormData.timeVerify = row.timeVerify;
}
// 删除确定按钮
const handleDelete = async  (index,row) =>{
  try {
    //调删除营销策略的接口
    const res  = await postDeleteMarketPloyInfo({marketPloyId: row.marketPloyId})
    console.log("删除结果",res)
    //删除以后重新请求表格数据，重新渲染页面
    await fetchData();
  }catch (error){
    console.log(error)
  }
}
// 删除取消按钮
const cancelEvent = () =>{}

// 请求营销策略表的数据
const fetchData = async () => {
  try {
    const res = await getMarketPloyInfo({ currentPage: pageData.currentPage, pageSize: pageData.pageSize });
    // 处理数据
    const data = transformArray(res.marketPloyInfo.list);
    console.log("转换申请状态等状态:",data)
    // 假设返回的数据结构包含marketPloyInfo.list 和 marketPloyInfo.total
    tableData.value = data; // 更新表格数据
    pageData.total = res.marketPloyInfo.total || 0; // 更新总条数
    console.log("表格数据",res.marketPloyInfo.list);
  } catch (error) {
    console.error('获取营销策略信息失败:', error);
  }
};
// 重置按钮
const resetForm = (form)=>{
  form.resetFields();
}
// 添加的提交按钮
const submitForm = async (form)=>{
  // console.log("提交表单",form)
  // form.ladderThreshold = convertToDesiredFormat(form.ladderThreshold)
  console.log("优惠阶梯格式化后：",convertToDesiredFormat(form.ladderThreshold))
  form.ladderThreshold = convertToDesiredFormat(form.ladderThreshold)
  console.log("转换后的数据",form)
  // 重新渲染页面
  // await getCompanyData();
  // 关闭对话框
  dialogFormVisible1.value = false;
  try {
    const res = await postAddMarketPloyInfo(form);
    // 调用 fetchData 函数来重新获取并更新表格数据
    await fetchData();
    console.log(res);
  }catch (err){
    console.log(err);
  }
}
// 处理阶梯优惠的数据
function convertToDesiredFormat(dataArray) {
  // 如果 dataArray 不是数组，则返回空对象
  if (!Array.isArray(dataArray)) {
    console.error('Expected an array but got:', dataArray);
    return {};
  }
  // const result = {};
  var result = new Map()
  dataArray.forEach(item => {
    // 检查必要的字段是否存在且不为 null
    if (
        item.startAmount !== null &&
        item.endAmountOrRate !== null &&
        item.description !== null &&
        item.description !== undefined
    ) {
      // 将 startAmount 和 endAmountOrRate 转换为固定小数位数的字符串
      const descriptionAmount = parseFloat(item.description).toFixed(2);
      const startAmount = parseFloat(item.startAmount).toFixed(2);
      const endAmountOrRate = parseFloat(item.endAmountOrRate).toFixed(2);
      // 将数据进行处理，使用对象形式，添加key与value
      result.set(descriptionAmount,[startAmount, endAmountOrRate]);
    }
  });
  var plain = Object.fromEntries(result);
  var result1={}
  result1 = JSON.stringify(plain)
  return result1.toString();
}
//获取公司信息
const getCompanyData = async () =>{
  try {
    const res = await getCustomerList();
    options.value = res.customerAccounts
    console.log("外部公司选项",options.value)
  } catch (error) {
    console.log(error);
  }
  try {
    const res = await initCompanySelectNoStation()
    insideOptions.value = res.companySelect
  } catch (error) {
    console.log(error);
  }
}
// 编辑的提交按钮
const updataForm = async (form)=>{
  console.log("编辑表单",form)
}
// 在组件挂载时加载数据
onMounted( () => {
  fetchData();
  getCompanyData();
});

</script>
<style lang="scss" scoped>
//最外层容器
.marketStrategy-container {
    //顶层进行左右布局
    .market-top {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .market-top-search {
      /* 搜索框样式 */
    }

      .market-top-btn {
      /* 按钮样式 */
    }
  }
  .market-table{
    display: flex;
  }
  .market-bottom{
    position: absolute;
    bottom: 20px;
  }
}
</style>